package maple.widgets;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

import com.phidgets.event.DetachEvent;
import com.phidgets.event.DetachListener;
import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;

import maple.util.Sensor;
import maple.util.Timestamp;

public class ConsoleLogger extends Object
{
	static final int INTERVAL = 60000;
	static final String DEVICE = "PhidgetInterfaceKit";
	static boolean _available = true;

	public static void main( String[] args ) throws ClassNotFoundException, PhidgetException
	{
		if( args.length >= 2 )
		{
			InterfaceKitPhidget handler = new InterfaceKitPhidget();
			handler.open( Integer.parseInt( args[ 0 ] ) );
			handler.waitForAttachment( 5000 );

			int exception = 0;

			if( handler.isAttached() )
			{
				int serial = handler.getSerialNumber();
				int size = handler.getSensorCount();

				String[] types = new String[ size ];
				types[ 0 ] = Sensor.Type.PHIDGET_HUMIDITY.toString();
				types[ 1 ] = Sensor.Type.PHIDGET_TEMPERATURE.toString();

				handler.setRatiometric( true );
				handler.addDetachListener( new DetachListener()
				{
					public void detached( DetachEvent e )
					{
						_available = false;
					}
				} );

				// connect to database
				Class.forName( "com.mysql.jdbc.Driver" );

				while( exception < 10 )
				{
					try
					{
						exception = 0;

						Connection database = DriverManager.getConnection( "jdbc:mysql://gardenia.csie.ntu.edu.tw:3306/maple", "maple", "dpsSjbMeKfXHaXzA" );
						PreparedStatement statement = database.prepareStatement( "INSERT INTO observations ( sensed_time, gateway, port, sensor, location, value, received_time ) values( ?, ?, ?, ?, ?, ?, ? )" );
						while( _available )
						{
							long current = System.currentTimeMillis();
							Long timestamp = Long.parseLong( Timestamp.Default.format( new Date( current ) ) ); 
							for( int i = 0; i < size; ++i )
							{
								String type = types[ i ];
								String location = args[ 1 ];

								if( !type.equals( "" ) && !location.equals( "" ) )
								{
									String value = Sensor.toString( type, "" + handler.getSensorValue( i ) );
									statement.setLong( 1, timestamp ); 
									statement.setString( 2, DEVICE + "_" + serial ); 
									statement.setString( 3, "A." + i ); 
									statement.setString( 4, type ); 
									statement.setString( 5, location ); 
									statement.setDouble( 6, Double.parseDouble( value ) ); 
									statement.setLong( 7, timestamp ); 
									statement.setQueryTimeout( 1 );
									statement.execute();
									statement.clearParameters();
									System.out.println( timestamp + " " + value );
								}
							}

							while( System.currentTimeMillis() - current < INTERVAL )
							{
							}
						}

						database.close();
					}
					catch( SQLException e )
					{
						++exception;
						e.printStackTrace();
					}
				}

				handler.close();
			}
		}
		else
		{
			System.out.println( "java -jar logger.jar [serial] [location]" );
		}
	}
}
